import 'package:efood_multivendor/controller/cart_controller.dart';
import 'package:efood_multivendor/controller/category_controller.dart';
import 'package:efood_multivendor/controller/restaurant_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/data/model/response/category_model.dart';
import 'package:efood_multivendor/data/model/response/product_model.dart';
import 'package:efood_multivendor/data/model/response/restaurant_model.dart';
import 'package:efood_multivendor/helper/date_converter.dart';
import 'package:efood_multivendor/helper/price_converter.dart';
import 'package:efood_multivendor/helper/responsive_helper.dart';
import 'package:efood_multivendor/helper/route_helper.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/images.dart';

import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/cart_view.dart';
import 'package:efood_multivendor/view/base/custom_image.dart';
import 'package:efood_multivendor/view/base/product_view.dart';
import 'package:efood_multivendor/view/screens/restaurant/product_search_result_screen.dart';
import 'package:efood_multivendor/view/screens/home/home_screen.dart';
import 'package:efood_multivendor/view/screens/restaurant/widget/category_list.dart';
import 'package:efood_multivendor/view/screens/restaurant/widget/restaurant_description_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:get/get.dart';

const _cardColor = LinearGradient(colors: [
  Color(0xffff8022),
  Color(0xffff2222),
]);
const _cardColor2 = LinearGradient(colors: [
  Color.fromARGB(255, 201, 201, 201),
  Color.fromARGB(255, 194, 194, 194),
]);
const _maxHeight = 350.0;
const _minHeight = 62.0;

class RestaurantScreen extends StatefulWidget {
  final Restaurant restaurant;
  RestaurantScreen({required this.restaurant});

  @override
  State<RestaurantScreen> createState() => _RestaurantScreenState();
}

class _RestaurantScreenState extends State<RestaurantScreen>
    with SingleTickerProviderStateMixin {
  final ScrollController scrollController = ScrollController();
  late AnimationController _controller;
  double _currentHeight = _minHeight;

  @override
  void initState() {
    super.initState();
    Get.find<SplashController>().setFirstOpen();
    Get.find<RestaurantController>().getRestaurantDetails(
        Restaurant(id: widget.restaurant.id), 'restaurant');
    if (Get.find<CategoryController>().categoryList == null) {
      Get.find<CategoryController>().getCategoryList(true);
    }
    Get.find<RestaurantController>()
        .getRestaurantProductList(widget.restaurant.id!, 1, 'all', false);
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
              scrollController.position.maxScrollExtent &&
          Get.find<RestaurantController>().restaurantProducts != null &&
          !Get.find<RestaurantController>().foodPaginate) {
        int pageSize =
            (Get.find<RestaurantController>().foodPageSize / 10).ceil();
        if (Get.find<RestaurantController>().foodOffset < pageSize) {
          Get.find<RestaurantController>()
              .setFoodOffset(Get.find<RestaurantController>().foodOffset + 1);
          Get.find<RestaurantController>().showFoodBottomLoader();
          Get.find<RestaurantController>().getRestaurantProductList(
            widget.restaurant.id!,
            Get.find<RestaurantController>().foodOffset,
            Get.find<RestaurantController>().type,
            false,
          );
        }
      }
    });
    _controller = AnimationController(
      animationBehavior: AnimationBehavior.preserve,
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );
  }

  @override
  void dispose() {
    super.dispose();

    scrollController.dispose();
    _controller.dispose();
  }

  void back() {
    Get.back();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CartController>(builder: (cartController) {
      return Scaffold(
        backgroundColor: Colors.white,
        body: GestureDetector(
          onPanUpdate: (details) {
            if (details.delta.dx > 0) {
              Get.back();
            }

            if (details.delta.dx < 0) {}
          },
          child: CartView(
              Stack(
                children: [
                  GetBuilder<RestaurantController>(builder: (restController) {
                    return GetBuilder<CategoryController>(
                        builder: (categoryController) {
                      bool isOpen = false;
                      Restaurant? _restaurant;
                      if (restController.restaurant != null &&
                          restController.restaurant?.name != null &&
                          categoryController.categoryList != null) {
                        _restaurant = restController.restaurant;

                        isOpen = restController.restaurant?.is_open == true;
                      }

                      restController.setCategoryList();

                      return (restController.restaurant != null &&
                              restController.restaurant?.name != null &&
                              categoryController.categoryList != null)
                          ? CustomScrollView(
                              physics: AlwaysScrollableScrollPhysics(),
                              controller: scrollController,
                              slivers: [
                                SliverAppBar(
                                  automaticallyImplyLeading: false,
                                  expandedHeight: 230,
                                  leadingWidth: 5.h,
                                  toolbarHeight: 50,
                                  elevation: 0,
                                  pinned: true,
                                  floating: false,
                                  backgroundColor: Colors.white,
                                  flexibleSpace: FlexibleSpaceBar(
                                    background: Stack(
                                      children: [
                                        Container(
                                          decoration: BoxDecoration(
                                              color: Colors.white),
                                          child: ClipRRect(
                                            borderRadius: BorderRadius.vertical(
                                                bottom: Radius.circular(10)),
                                            clipBehavior: Clip.antiAlias,
                                            child: CustomImage(
                                              height: 35.h,
                                              width: double.infinity,
                                              fit: BoxFit.cover,
                                              placeholder:
                                                  Images.restaurant_cover,
                                              image:
                                                  '${_restaurant?.coverPhoto}',
                                            ),
                                          ),
                                        ),
                                        ClipRRect(
                                          borderRadius:
                                              BorderRadius.circular(10),
                                          clipBehavior: Clip.antiAlias,
                                          child: Container(
                                            height: 35.h,
                                            decoration: BoxDecoration(
                                              gradient: LinearGradient(
                                                begin: Alignment.topCenter,
                                                end: Alignment.bottomCenter,
                                                colors: [
                                                  Colors.black.withOpacity(0.5),
                                                  Colors.transparent,
                                                  Colors.black.withOpacity(0.5),
                                                ],
                                              ),
                                            ),
                                          ),
                                        ),
                                        Positioned(
                                          bottom: 5,
                                          child: Padding(
                                            padding: EdgeInsets.only(
                                                left: 5.w, bottom: 1.h),
                                            child: Row(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                ClipRRect(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          2.h),
                                                  clipBehavior: Clip.hardEdge,
                                                  child: CustomImage(
                                                    image: _restaurant!.logo!,
                                                    height: 8.h,
                                                    width: 8.h,
                                                  ),
                                                ),
                                                SizedBox(width: 5),
                                                Padding(
                                                  padding: EdgeInsets.only(
                                                      top: 0.7.h),
                                                  child: Column(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment.start,
                                                    crossAxisAlignment:
                                                        CrossAxisAlignment
                                                            .start,
                                                    children: [
                                                      Text(
                                                        _restaurant.name ?? '',
                                                        style: sfBlack.copyWith(
                                                          color: Colors.white,
                                                          fontSize: 18,
                                                        ),
                                                      ),
                                                      SizedBox(height: 0.6.h),
                                                      Row(
                                                        children: [
                                                          Icon(
                                                            FeatherIcons.mapPin,
                                                            color: Colors.white,
                                                            size: 2.h,
                                                          ),
                                                          SizedBox(width: 10),
                                                          SizedBox(
                                                            width: 69.w,
                                                            child: Text(
                                                              _restaurant
                                                                      .address ??
                                                                  "No address set",
                                                              style: sfRegular
                                                                  .copyWith(
                                                                color: Colors
                                                                    .white,
                                                              ),
                                                            ),
                                                          ),
                                                        ],
                                                      ),
                                                      SizedBox(height: 1.h),
                                                      Container(
                                                        height: 3.h,
                                                        width: 25.w,
                                                        decoration:
                                                            BoxDecoration(
                                                          borderRadius:
                                                              BorderRadius
                                                                  .circular(4),
                                                          color: Colors.grey
                                                              .withOpacity(0.5),
                                                        ),
                                                        child: Row(
                                                          mainAxisAlignment:
                                                              MainAxisAlignment
                                                                  .center,
                                                          children: [
                                                            Container(
                                                              height: 0.7.h,
                                                              width: 0.7.h,
                                                              decoration:
                                                                  BoxDecoration(
                                                                borderRadius:
                                                                    BorderRadius
                                                                        .circular(
                                                                            10),
                                                                color: isOpen ==
                                                                        true
                                                                    ? Theme.of(
                                                                            context)
                                                                        .secondaryHeaderColor
                                                                    : Colors
                                                                        .red,
                                                              ),
                                                            ),
                                                            SizedBox(
                                                                width: 1.w),
                                                            Text(
                                                              isOpen
                                                                  ? "open_now"
                                                                      .tr
                                                                  : "closed_now"
                                                                      .tr,
                                                              style: sfBold
                                                                  .copyWith(
                                                                color: isOpen
                                                                    ? Theme.of(
                                                                            context)
                                                                        .secondaryHeaderColor
                                                                    : Colors
                                                                        .red,
                                                              ),
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                )
                                              ],
                                            ),
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                  leading: Padding(
                                    padding: EdgeInsets.only(left: 2.5.w),
                                    child: GestureDetector(
                                      onTap: () {
                                        if (!cartController.isCartOpen) {
                                          if (Get.find<SplashController>().showType != null &&
                                              Get.find<SplashController>()
                                                      .showType !=
                                                  null &&
                                              Get.find<SplashController>()
                                                      .showType
                                                      ?.isNotEmpty ==
                                                  true) {
                                            Get.find<SplashController>()
                                                .setNotificationPayload("", "");
                                            Get.find<SplashController>()
                                                .loadData(false);
                                            Get.offNamed(
                                                RouteHelper.getInitialRoute(
                                                    "saved address found"));
                                          } else {
                                            Get.back();
                                          }
                                        } else {
                                          cartController.closeCart();
                                        }
                                      },
                                      child: Container(
                                        width: 4.h,
                                        decoration: BoxDecoration(
                                          shape: BoxShape.circle,
                                          color: Colors.white.withOpacity(0.7),
                                        ),
                                        child: Center(
                                          child: Icon(
                                            Icons.chevron_left,
                                            color: Colors.black,
                                            size: 3.h,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                  actions: [
                                    GestureDetector(
                                      onTap: () {
                                        Get.to(ProductSearchResultScreen(
                                          restaurant: _restaurant,
                                        ));
                                      },
                                      child: Padding(
                                        padding: EdgeInsets.only(right: 2.5.w),
                                        child: Container(
                                          width: 4.h,
                                          decoration: BoxDecoration(
                                            shape: BoxShape.circle,
                                            color:
                                                Colors.white.withOpacity(0.7),
                                          ),
                                          child: Center(
                                            child: Icon(
                                              Icons.search,
                                              color: Colors.black,
                                              size: 3.h,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                                SliverToBoxAdapter(
                                    child: Center(
                                        child: Container(
                                  width: Dimensions.WEB_MAX_WIDTH,
                                  padding: EdgeInsets.all(
                                      Dimensions.PADDING_SIZE_SMALL),
                                  color: Colors.white,
                                  child: Column(children: [
                                    ResponsiveHelper.isDesktop(context)
                                        ? SizedBox()
                                        : RestaurantDescriptionView(
                                            restaurant: _restaurant),
                                    _restaurant.discount != null
                                        ? Container(
                                            width: context.width,
                                            margin: EdgeInsets.symmetric(
                                                vertical: Dimensions
                                                    .PADDING_SIZE_SMALL),
                                            decoration: BoxDecoration(
                                                borderRadius:
                                                    BorderRadius.circular(
                                                        Dimensions
                                                            .RADIUS_SMALL),
                                                gradient: _cardColor),
                                            padding: EdgeInsets.all(
                                                Dimensions.PADDING_SIZE_SMALL),
                                            child: Column(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.center,
                                                children: [
                                                  Text(
                                                    _restaurant.discount
                                                                ?.discountType ==
                                                            'percent'
                                                        ? '${_restaurant.discount!.discount}% OFF'
                                                        : '${PriceConverter.convertPrice(_restaurant.discount!.discount!)} OFF',
                                                    style: sfMedium.copyWith(
                                                        fontSize: Dimensions
                                                            .fontSizeLarge,
                                                        color: Theme.of(context)
                                                            .cardColor),
                                                  ),
                                                  Text(
                                                    _restaurant.discount
                                                                ?.discountType ==
                                                            'percent'
                                                        ? '${'enjoy'.tr} ${_restaurant.discount!.discount}% ${'off_on_all_categories'.tr}'
                                                        : '${'enjoy'.tr} ${PriceConverter.convertPrice(_restaurant.discount!.discount!)}'
                                                            ' ${'off_on_all_categories'.tr}',
                                                    style: sfMedium.copyWith(
                                                        fontSize: Dimensions
                                                            .fontSizeSmall,
                                                        color: Theme.of(context)
                                                            .cardColor),
                                                  ),
                                                  Text(
                                                    '[ ${'daily_time'.tr}: ${DateConverter.convertTimeToTime(_restaurant.discount!.startTime!)} '
                                                    '- ${DateConverter.convertTimeToTime(_restaurant.discount!.endTime!)} ]',
                                                    style: sfRegular.copyWith(
                                                        fontSize: Dimensions
                                                            .fontSizeExtraSmall,
                                                        color: Theme.of(context)
                                                            .cardColor),
                                                  ),
                                                ]),
                                          )
                                        : SizedBox(),
                                  ]),
                                ))),
                                (restController.categoryList?.isNotEmpty ==
                                        true)
                                    ? SliverPersistentHeader(
                                        pinned: true,
                                        delegate: SliverDelegate(
                                            child: Column(children: [
                                          Container(
                                            height: 5.h,
                                            width: Dimensions.WEB_MAX_WIDTH,
                                            color: Colors.white,
                                            padding: EdgeInsets.symmetric(
                                              vertical: Dimensions
                                                  .PADDING_SIZE_EXTRA_SMALL,
                                            ),
                                            child: ListView.builder(
                                              scrollDirection: Axis.horizontal,
                                              itemCount: restController
                                                      .categoryList?.length ??
                                                  0,
                                              padding: EdgeInsets.only(
                                                  left: Dimensions
                                                      .PADDING_SIZE_SMALL),
                                              physics: BouncingScrollPhysics(),
                                              itemBuilder: (context, index) {
                                                return CategoryTabItem(
                                                    index: index,
                                                    restController:
                                                        restController);
                                              },
                                            ),
                                          ),
                                        ])),
                                      )
                                    : SliverToBoxAdapter(child: SizedBox()),
                                SliverToBoxAdapter(
                                    child: SizedBox(
                                  height: 2.h,
                                )),
                                SliverToBoxAdapter(
                                    child: Center(
                                        child: Container(
                                  width: Dimensions.WEB_MAX_WIDTH,
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                  ),
                                  child: Column(children: [
                                    ProductView(
                                      fromRestaurant: true,
                                      isRestaurant: false,
                                      restaurants: null,
                                      products: restController
                                                  .categoryList?.isNotEmpty ==
                                              true
                                          ? restController.restaurantProducts
                                          : null,
                                      inRestaurantPage: true,
                                      type: restController.type,
                                      onVegFilterTap: (String type) {
                                        restController.getRestaurantProductList(
                                            restController.restaurant!.id!,
                                            1,
                                            type,
                                            true);
                                      },
                                      padding: EdgeInsets.symmetric(
                                        horizontal:
                                            Dimensions.PADDING_SIZE_SMALL,
                                        vertical:
                                            ResponsiveHelper.isDesktop(context)
                                                ? Dimensions.PADDING_SIZE_SMALL
                                                : 0,
                                      ),
                                    ),
                                    restController.foodPaginate
                                        ? Center(
                                            child: Padding(
                                                padding: EdgeInsets.all(
                                                    Dimensions
                                                        .PADDING_SIZE_SMALL),
                                                child: CircularProgressIndicator
                                                    .adaptive(
                                                  backgroundColor:
                                                      Theme.of(context)
                                                          .colorScheme
                                                          .secondary,
                                                )))
                                        : SizedBox(),
                                  ]),
                                ))),
                              ],
                            )
                          : Center(
                              child: CircularProgressIndicator.adaptive(
                                backgroundColor:
                                    Theme.of(context).colorScheme.secondary,
                              ),
                            );
                    });
                  }),
                ],
              ),
              widget.restaurant.deliveryFee.toString(),
              restaurantId: widget.restaurant.id),
        ),
      );
    });
  }
}

class SliverDelegate extends SliverPersistentHeaderDelegate {
  Widget child;

  SliverDelegate({required this.child});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return child;
  }

  @override
  double get maxExtent => 50;

  @override
  double get minExtent => 50;

  @override
  bool shouldRebuild(SliverDelegate oldDelegate) {
    return oldDelegate.maxExtent != 50 ||
        oldDelegate.minExtent != 50 ||
        child != oldDelegate.child;
  }
}

class CategoryProduct {
  CategoryModel category;
  List<Product> products;
  CategoryProduct(this.category, this.products);
}
